import type { RouteRecordRaw } from 'vue-router'

import router from '@/router'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { useUserStoreWithOut } from '@fl/store/modules/user'

// 根据角色设置路由
export async function setRoutesByRole() {
    const userStore = useUserStoreWithOut()
    const permissionStore = usePermissionStoreWithOut()

    const userInfo = userStore.getUserInfo

    const { sysUser: { roles } } = userInfo as any

    const currentRole = roles?.[0]
    let roleRouters = [] as string[]

    if (currentRole) {
        const roleKey = currentRole.roleKey

        // 采购商
        if (roleKey === 'purchaser') {
            roleRouters = ['/purchase-pages']
        }
        // 供应商
        else if (roleKey === 'supplier') {
            roleRouters = ['/supplier-pages']
        }
        // 运营官
        else if (roleKey === 'operationer') {
            roleRouters = ['/operations-pages']
        }

        userStore.setRoleRouters(roleRouters)

        // 追加路由
        await permissionStore.generateRoutes('frontEnd', roleRouters as string[]).catch(() => {})
        permissionStore.getAddRouters.forEach((route) => {
            router.addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
        })
        permissionStore.setIsAddRouters(true)

        if (roleKey === 'operationer') {
            // 运营官进到后台页面去
            // 提前把分片路由切一刀, 免得侧边栏空白
            permissionStore.setSliceRouters('/operations-pages')
            router.push({ path: permissionStore.addRouters[0].path })
            return
        }
    }
    router.push('/')
}
